import { calcTime, proxy, reqHeader } from '../../utils/util.js';
import LoginStore from '../../pages/login/store.js';
Component({
  properties: {
    popParams:{
      type: Object,
      value: {},
      observer: function (newVal, oldVal, changedPath) {
        this._loadData(newVal);
      }
    }
  },
  attached:function(){
    wx.getSystemInfo({
      success: (res) => {
        let IPhoneX = false;
        if (res.model.search('iPhone X') != -1) {
          IPhoneX = true;
        }
        this.setData({
          IPhoneX: IPhoneX
        })
      }
    });
  },
  data: {
    placeHoldertext:'添加您的评论...',
    fanyiText:'译',
    listData: [],
    page: 1,
    hasNext: true,
    focusStatus:false,
    inputComments:'',
    inputCommentsList:[],
    addParams:{},
    replyFocus:false,
    likeOutLineSvg:'https://cdn.500px.me/images/WeChat/like-outline.svg',
    likeFillSvg:'https://cdn.500px.me/images/WeChat/like-filled.svg',
    fanyiIcon1:'https://cdn.500px.me/images/WeChat/translate.svg',
    fanyiIcon2: 'https://cdn.500px.me/images/WeChat/translate-2.svg',
    scrollTop:0,
  },
  methods: {
    fanyiFun:function(commentId,callback){
      let userAccountInfo = LoginStore.userInfo;
      wx.request({
        url: `${proxy}/community/comment/fanyi`,
        data:{
          id: commentId,
          access_token: userAccountInfo.access_token
        },
        header:reqHeader,
        success: function (res) {
          res = res.data;
          if(res.status == 200){
            callback(res.data)
          }
        }
      });
    },
    cTranslate:function(){
      if (this.data.fanyiText === '原'){
        let initComment = this.data.initComment;
        let initStr = '';
        for (let item of initComment) {
          initStr += item.text;
        }
        this.setData({
          inputComments: initStr,
          inputCommentsList: this.data.initComment,
          fanyiText: '译'
        });
        return;
      }
      if (!this.data.inputComments){
        return;
      }
      let me = this;
      let initCommentsList = this.data.inputCommentsList;
      let content = '';
      for (let item of initCommentsList){
        if(item.type == 'text'){
          content+=item.text;
        }
      }
      me.fanyiFun(content,function(data){
        me.setData({
          inputComments: data,
          inputCommentsList: [{
            type:'text',
            text:data
          }],
          initComment: initCommentsList,
          fanyiText: '原'
        });
      });
    },
    selectCommentItem:function(e){
      let me = this;
      let userAccountInfo = LoginStore.userInfo;
      let data = e.currentTarget.dataset;
      if ((userAccountInfo.userId == this.properties.popParams.uploaderId) || (userAccountInfo.userId == data.userid)) {
        wx.showModal({
          title: '提示',
          content: '是否删除该评论？',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              me.delComment(data, userAccountInfo);
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        })
      }
    },
    selectReply:function(e){
      let data = e.currentTarget.dataset;
      this.setData({
        replyFocus:true,
        focusStatus: true,
        addParams: {
          toUserId: data.userid,
          parentId: data.parentid,
          nickName: data.nickname,
          key: data.key
        }
      });
    },
    delComment: function (p, userAccountInfo){
      wx.showLoading({
        title: 'loading...',
        mask:true
      });
      let me = this;
      wx.request({
        url: `${proxy}/community/comment/del`,
        data: {
          commentId: p.commentid || p.parentid ,
          access_token: userAccountInfo.access_token
        },
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200) {
            let listData = me.data.listData;
            if (p.childkey !=undefined){
              listData[p.key].childComments.splice(p.childkey,1);
            }else{
              listData.splice(p.key,1);
            }
            me.setData({
              listData: listData,
              commentCount: --me.data.commentCount
            },function(){
              wx.hideLoading();
            })
          } else {
            console.log(res.message);
          }
        }
      });
    },
    addComment:function(){
      if (!this.data.inputComments) {
        return;
      }
      wx.showLoading({
        title: 'loading...',
        mask: true
      });
      let p = this.data.addParams;
      let me = this;
      let userAccountInfo = LoginStore.userInfo;
      let inputCommentsList = this.data.inputCommentsList;
      let messageStr = "";
      for (let item of inputCommentsList){
        if (item.type == 'user'){
          messageStr += `<a px_tag="at" href="${proxy}/community/user-details/${item.userId}" target="_Blank" user_id="${item.userId}"> ${item.text} </a>`
        }else{
          messageStr+=item.text
        }
      }
      let params={
        message: messageStr,
        resId: this.properties.popParams.id,
        access_token: userAccountInfo.access_token
      };
      if (p.toUserId){
        params.toUserId = p.toUserId;
        params.parentId = p.parentId;
      }
      wx.request({
        url: `${proxy}/community/comment/add`,
        data: params,
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200){
            let listData = me.data.listData;
            me.circulation(res.data);
            let setObj = {
              listData: listData,
              focusStatus: false,
              inputComments: '',
              inputCommentsList: [],
              addParams: {},
              replyFocus: false,
              commentCount: ++me.data.commentCount,
              initComment: null,
              fanyiText: "译"
            }
            if (p.toUserId){
              listData[p.key].childComments.push(res.data);
            }else{
              res.data.allReply = false;
              listData.unshift(res.data);
              setObj.scrollTop = 0;
            }
            setObj.listData = listData;
            
            me.setData(setObj,function(){
              wx.hideLoading()
            })
          }else{
            console.log(res.message);
          }
        }
      });
    },
    focusHandler:function(){
      this.setData({
        focusStatus:true
      })
    },
    clickMask: function () {
      this.setData({
        focusStatus: false,
        addParams: {},
        replyFocus: false,
      })
    },
    blurHandler:function(e){
      this.setData({
        focusStatus: false
      })
    },
    changeInputList: function (type, pos, endPos, newContent) {
      let inputList = this.data.inputCommentsList;
      let inputValue = this.data.inputComments;
      let calcPos = -1;
      for (let i = 0; i < inputList.length; i++) {
        let item = inputList[i];
        let tplPos = calcPos;
        calcPos += item.text.length;
        if(type == 'delete'){
          if (pos <= tplPos && endPos > calcPos) {
            delete inputList[i];
            continue;
          }
          let startStr = null;
          if (pos > tplPos && pos <= calcPos){
            if (item.type == 'user'){
              delete inputList[i];
            }else{
              let start = pos - tplPos - 1;
              startStr = item.text.slice(0, start);
            }
          }
          if (endPos > tplPos && endPos <= calcPos){
            if (item.type == 'user') {
              delete inputList[i];
            } else {
              let end = endPos - tplPos - 1;
              if (startStr == null){
                item.text = item.text.slice(end + 1);
              }else{
                item.text = startStr + item.text.slice(end + 1);
              }
            }
            break;
          } else if (startStr != null){
            item.text = startStr;
          }
        }else{
          if (pos <= calcPos){
            if (item.type == 'text'){
              let itemPos = pos - tplPos - 1;
              item.text = item.text.slice(0, itemPos) + newContent + item.text.slice(itemPos);
            } else if (inputValue[pos] == '@'){
              inputList.splice(i, 0, {
                type: 'text',
                text: newContent
              });
            }
            break;
          }
        }
      }

      if(type == 'add'){
        return inputList
      }else{
        let list = [];
        for (let listItem of inputList) {
          if (listItem != undefined && listItem.text) {
            list.push(listItem)
          }
        }
        return list;
      }
    },
    inputComment:function(e){
      let inputList = this.data.inputCommentsList;
      let inputValue = this.data.inputComments;
      let value = e.detail.value;
      let pos = e.detail.cursor;
      if (value.length < inputValue.length) {
        //删除
        let count = inputValue.length - value.length;
        let endPos = pos+count-1;
        inputList = this.changeInputList('delete', pos, endPos);
      } else if (value.length > inputValue.length) {
        //增加
        let count = value.length - inputValue.length;
        let startPos = pos - count;
        let newContent = value.slice(startPos, pos);
        if (startPos > (inputValue.length - 1)) {
          inputList.push({
            type: 'text',
            text: newContent
          })
        } else {
          inputList = this.changeInputList('add', startPos, null,newContent);
        }
      } else {
        console.log('no delete and no add');
      }
      let newStr = '';
      for (let item of inputList){
        newStr += item.text;
      }
      this.setData({
        inputCommentsList: inputList,
        inputComments: newStr
      });
    },
    scrollList:function(){
      if (this.data.hasNext){
        this._loadData(this.properties.popParams);
      }

    },
    dingWei:function(e,callback){
      let data = e.currentTarget.dataset;
      let index = data.key;

      let listData = this.data.listData;
      let dingwei = listData[index];
      if (data.childkey !== undefined) {
        let idx = data.childkey;
        dingwei = listData[index].childComments[idx];
      }
      callback(dingwei);
      this.setData({
        listData: listData
      });
    },
    translate:function(e){
      let data = e.currentTarget.dataset;
      let item = data.item;
      // let message = '';
      // if (item.msgTextList.length){
      //   for (let v of item.msgTextList){
      //     if(v.type == 'text'){
      //       message+=v.desc;
      //     }
      //   }
      // }else{
      //   message = item.message;
      // }
      this.fanyiFun(item.id,(data)=>{
        this.dingWei(e, function (dingwei) {
          dingwei.hastranslated = true;
          dingwei.messageFanyi2 = data;
          dingwei.showFanyi = false;
        });
      });
      
    },
    isShowFanyi: function (message){
      let reg = /([a-zA-Z]){2,}/;
      if (message.match(reg)){
        return true;
      }else{
        return false;
      }
    },
    resolveMessage: function (message,isFanyi){
      let msgTextList = [];
      let msgPhotoList = [];
      let tplMsgStr = '';
      let messageList = JSON.parse(message);
      messageList.forEach((itemMsg, index) => {
        if (itemMsg.type == 'text') {
          let desc = itemMsg.description;
          let resultObj = this.resolveMsg(desc);
          msgTextList = resultObj.msgTextList;
          tplMsgStr = resultObj.tplMsgStr;
        } else if (itemMsg.type == 'photo') {
          msgPhotoList.push(itemMsg);
        }
      });

      if (isFanyi){
        return msgTextList
      }else{
        return {
          msgTextList: msgTextList,
          msgPhotoList: msgPhotoList,
          tplMsgStr: tplMsgStr
        }
      }
    },
    resolveMsg:function(desc){
      let msgTextList = [];
      let tplMsgStr = '';
      let res = desc.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="[^"]+">[\s\S]*?<\/a>/gi);
      if (res != null) {
        let resList = desc.split(/(<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="[^"]+">[\s\S]*?<\/a>)/);
        resList.forEach((value, i) => {
          if (value) {
            let hasA = value.match(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="[^"]+">[\s\S]*?<\/a>/gi);
            if (hasA != null) {
              let splitRes = value.split(/<a\b[^>]+\bhref="[^"]*"[^>]*\buser_id="([^"]+)">([\s\S]*?)<\/a>/);
              let descStr = splitRes[2];
              if (!msgTextList.length) {
                descStr = descStr.replace(/(^\s*)/g, "");
              };
              msgTextList.push({
                type: 'user',
                desc: descStr,
                id: splitRes[1]
              })
            } else {
              msgTextList.push({
                type: 'text',
                desc: value
              });
              tplMsgStr += value;
            }
          }
        })

      } else {
        msgTextList.push({
          type: 'text',
          desc: desc
        });
        tplMsgStr += desc;
      }

      return {
        msgTextList,
        tplMsgStr
      }
    },
    circulation:function(item){
      let that = this;
      if(item.type == 4){
        let messageRes = this.resolveMessage(item.message,false);
        item.msgPhotoList = messageRes.msgPhotoList;
        item.msgTextList = messageRes.msgTextList;
        item.showFanyi = this.isShowFanyi(messageRes.tplMsgStr);
      }else {
        let messageRes = this.resolveMsg(item.message);
        item.msgTextList = messageRes.msgTextList;
        item.showFanyi = this.isShowFanyi(messageRes.tplMsgStr);
      }
      item.createDate = calcTime(new Date(item.createDate));
      
      if (!item.userInfo.avatar.a1){
        item.userInfo.avatar.a1 = 'https://img.500px.me/default_tx.png!a1';
      }
    },
    _loadData: function (popParams) {
      let me = this;
      let userAccountInfo = LoginStore.userInfo;
      let urlStr = `${proxy}/community/comment/list`;
      wx.request({
        url: urlStr,
        data: {
          resId: popParams.id,
          page: this.data.page,
          size: 20,
          type: 'json',
          access_token: userAccountInfo.access_token
        },
        header: reqHeader,
        success: function (res) {
          res = res.data;
          if (res.status == 200){
            let hasNext = true;
            if (!res.comments.length) {
              hasNext = false;
            }

            for (let item of res.comments) {
              me.circulation(item);
              if (item.childComments.length){
                for (let childItem of item.childComments){
                  me.circulation(childItem);
                }
                item.allReply = false;
              }
            }
            let listData = me.data.listData.concat(res.comments);
            me.setData({
              listData: listData,
              page: ++me.data.page,
              hasNext: hasNext,
              commentCount: res.commentCount
            })
          }else{
            console.log(res.message);
          }
        }
      });
    },
    viewAllReply:function(e){
      let data = e.currentTarget.dataset;
      let index = data.key;
      let listData = this.data.listData;
      listData[index].allReply = true;
      this.setData({
        listData: listData
      })
    },
    toUserPage:function(e){
      let data = e.currentTarget.dataset;
      let item = data.item;
      if (item.type == 'text'){
        return;
      }
      wx.navigateTo({
        url: '/pages/userInfo/userInfo?userId=' + item.id
      })
    },
    likeHandler:function(e){
      var me = this;
      let data = e.currentTarget.dataset;
      let item = data.itemdata;
      let likeStr = 'like';
      if(item.like){
        likeStr = 'unlike';
      }

      wx.request({
        url: `${proxy}/community/comment/${likeStr}`,
        method: 'POST',
        data: {
          resourceId: this.properties.popParams.id,
          commentId: item.id,
          like:!item.like,
          access_token: LoginStore.userInfo.access_token
        },
        header: Object.assign({
          'content-type': 'application/x-www-form-urlencoded'
        }, reqHeader),
        success: function (data) {
          let res = data.data;
          if(res.message == 'ok'){
            me.dingWei(e, function (dingwei) {
              dingwei.like = !item.like;
              if (likeStr == 'like'){
                dingwei.countLike += 1;
              }else{
                dingwei.countLike -= 1;
              }
            });
          }
          
        },
        fail: function (e) {
          console.log(e);
        }
      })
    },
    toAtPage:function(){
      wx.navigateTo({
        url: '/pages/atPeople/atPeople',
      })
    },
    addAtPeople:function(param,callback){
      let list = this.data.inputCommentsList;
      list.push({
        type:'user',
        text: `@${param.nickName}`,
        userId: param.id
      })
      let newStr = '';
      for (let item of list) {
        newStr += item.text;
      }
      this.setData({
        inputCommentsList: list,
        inputComments: newStr,
      },function(){
        callback();
      });
      
    },
    toBlackPage:function(e){
      let data = e.currentTarget.dataset;
      let selectedNum = data.key;
      let list = data.list;
      let resourceType, photoList='';
      if(list.length == 1){
        resourceType = 0;
        photoList = list[0].url;
      }else{
        resourceType = 2;
        for(let item of list){
          photoList+=`${item.url},`
        }
      }
      wx.navigateTo({
        url: `/pages/groupFull/groupFull?photoList=${photoList}&resourceType=${resourceType}&selectedNum=${selectedNum}&fromPage=comments`,
      })
    },
    scrollView:function(e){
      // this.setData({
      //   scrollTop:e.detail.scrollTop
      // })
    },
    closePop: function () {
      this.triggerEvent('closepopevent', { curCommentCount: this.data.commentCount}, { bubbles: true, composed: true })
    }
  }
})
